<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;

use Think\Controller;

/**
 * 前台公共控制器
 * 为防止多分组Controller名称冲突，公共Controller名称统一使用分组名称
 */
class HomeController extends Controller
{

    public $TOKEN_KEY = '0ca175b71ucujb';
    public $user_info = [];
    public $APPLET_APPID = "wx7bffcd11b785251e";                        //小程序 appid
    public $APPLET_SECRET = "e1f5bca22a5e430fa3d44822d9d803d2";         //小程序 secret
    public $img_url = "";
    protected function _initialize(){
        $this->img_url = $_SERVER['SERVER_NAME'];
    }


    public function is_login($token = ''){
        //解密token
        $requestdata = file_get_contents("php://input");
        $paramData = json_decode($requestdata, true);
        $result = $this->decodeUserToken($token?$token:$paramData['token']);
        if($result['code'] == 401) {
           $this->throw_exception('签名有误');
        }else if($result['code'] == 402){
            $this->throw_exception('登录已过期,请重新登录');
        }
        $user_id = $result['data']['user_id'];
        $model = D("User");
        $params = ['user_id'=>$user_id,'status'=>1];
        $this->user_info = $model->get_user_info($params);
        if(empty($this->user_info)) $this->throw_exception('该员工已禁用');
    }


    //获取员工加密jwt token
    public function getLoginToken($user_info){
        vendor("JWT.JWT");
        $now_time = time();
        $token_data = array(
            'iat'   =>  $now_time, //签发时间
            'nbf'   =>  $now_time, //生效时间
            'exp'   =>  $now_time+3600*24*365,//实效2天
            'data'  =>  [
                'user_id'    => $user_info['id'],
                'user_name'  => $user_info['user_name'],
                'login_name' => $user_info['login_name']
            ]
        );
        $jwt = new \firebase\JWT\JWT();
        $jwt_token = $jwt->encode($token_data,$this->TOKEN_KEY,'HS256');
        return $jwt_token;
    }

    //这个是解密token函数
    public function decodeUserToken($token){
        vendor("JWT.JWT");
        vendor("JWT.Key");
        $jwt = new \firebase\JWT\JWT();
        $result = $jwt->decode($token, new \firebase\JWT\Key($this->TOKEN_KEY, 'HS256'));
        if(is_array($result) && $result['code'] == 401) return ['code' => 401,'msg'=>$result];   //验签失败

        if ($result->exp <= time()) {
            return ['code' => 402];   //过期时间小于当前时间
        } else {
            return ['code' => 200,
                'data' => [
                    'user_id'    => $result->data->user_id,
                    'user_name'  => $result->data->user_name,
                    'login_name' => $result->data->login_name
                ]
            ];
        }
    }


    /**
     * 接口抛出异常信息
     */
    function throw_exception($msg = "", $code = 500,$data = [])
    {
        $returnData['code'] = $code;
        $returnData['msg']  = $msg;
        $returnData['data'] = $data;
        exit(json_encode($returnData));
    }


    //上传图片
    public function upload($name = 'file'){
        if(!empty($_FILES[$name]['name'])) {
            $config = array(
                'maxSize'     =>  3145728,    // 设置附件上传大小
                'rootPath'    =>  './Uploads/', // 设置附件保存路径
                'saveName'    =>  array('uniqid', ''), // 保存为当前时间戳加随机串的形式
                'savePath'    =>  '', // 保存路径
                'ext'         =>  'jpg,gif,png,jpeg,bmp,swf', // 文件允许上传的类型
                'autoSub'     =>  true, // 启用子目录保存文件
                'subName'     =>  array('date', 'Ymd'), // 子目录创建方式，[0]-按年月  [1]-指定格式
            );
            $dir = "./Uploads/".date('Ymd');
            if (!is_dir($dir)) {
                mkdir($dir, 0777, true);
            }


            $exts = [
                'jpg', 'gif','png','jpeg','bmp','swf'
            ];
            // 实例化上传类
            $upload = new \Think\Upload($config);
            // 上传文件
            $info = $upload->uploadOne($_FILES[$name]);
            if(!in_array($info['ext'],$exts)){
                return [
                    'code' => 500,'msg' => '只能上传jpg,gif,png,jpeg,bmp,swf格式图片'
                ];
            }

            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            if ($info) {
                // 上传成功，返回信息
                return [
                    'code' => 200,
                    'data' => $protocol.$this->img_url."/Uploads/{$info['savepath']}{$info['savename']}",
                ];
            } else {
                // 上传失败，返回错误信息
                return [
                    'code' => 500,'msg' => $upload->getError()
                ];
            }
        }else{
            return [
                'code' => 500,'msg' => '请选择要上传的文件'
            ];
        }
    }


    //获取小程序token
    public function getAppletToken($appid, $secret, $filename = 'applet_token.json', $grant_type = "client_credential")
    {
        $file   = "./Public/static/{$filename}";
        $result = json_decode(file_get_contents($file, true), true);
        if (time() > $result['expires']) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type={$grant_type}&appid={$appid}&secret={$secret}";
            $result = json_decode($this->httpRequest($url), true);
            $returnData = [
                'access_token' => $result['access_token'] ? $result['access_token'] : null,
                'expires'      => $result['access_token'] ? time() + 1800 : 0,
            ];
            file_put_contents($file, json_encode($returnData));
        }
        return $result['access_token'];
    }

    public function httpRequest($url, $data = '', $method = 'GET', $HTTPHEADER = '')
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        if ($HTTPHEADER) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $HTTPHEADER);
        } else {
            curl_setopt($curl, CURLOPT_HEADER, 0);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }



    //execl下载
    public function execl_down($header = [], $list = [], $filename = "execl.xlsx", $file = "template_public.xlsx",$width_header = [])
    {
        vendor("PHPExcel.PHPExcel");
        $objPHPExcel = \PHPExcel_IOFactory::load('Public/static/' . $file);
        $worksheet = $objPHPExcel->getActiveSheet();
        array_unshift($list, $header);
        $keys    = array_keys($header);
        $total = 0;
        $cell_key = [];
        for ($i = 'A'; $i <= 'Z'; $i++) {
            if ($total < count($keys)) {
                $cell_key[] = $i;
                $total++;
            } else {
                break;
            }
        }
        foreach ($list as $a_key => $a_val) {
            foreach ($keys as $b_key => $b_val) {
                if($width_header[$b_val]){
                    $worksheet->getColumnDimension($cell_key[$b_key])->setWidth($width_header[$b_val]);
                }
                $worksheet->setCellValue($cell_key[$b_key] . ($a_key + 1), $a_val[$b_val]);
            }
        }

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename={$filename}");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objWriter->save('php://output');
    }
}


